from pickle import loads
from pickle import dumps
from functools import wraps
from random import randint

from django.core.cache import caches
from django.shortcuts import redirect, render

from common.models import User

MODEL_CACHE_KEY = 'house:modelcache:%s'


def my_model_cache(cache='default', timeout=None, *, key):
    """自定义实现模型缓存装饰器"""

    def decorator(func):

        def wrapper(*args, **kwargs):
            real_key = '%s:%s' % (MODEL_CACHE_KEY % key, ':'.join(map(str, args)))
            serialized_data = caches[cache].get(real_key)
            if serialized_data:
                data = loads(serialized_data)
            else:
                data = func(*args, **kwargs)
                if data:
                    caches[cache].set(real_key, dumps(data), timeout=timeout)
            return data

        return wrapper

    return decorator


def my_login_required(view_func):
    """自定义登录验证装饰器"""

    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        userid = request.session.get('userid')
        if userid:
            return view_func(request, *args, **kwargs)
        else:
            return redirect('/user/login')

    return wrapper


# def check_perm(resource):
#     """自定义用户操作权限检查装饰器"""
#
#     def decorater(view_func):
#
#         def wrapper(request, *args, **kwargs):
#             userid = request.session['userid']
#             user = get_user(userid)
#             if user.has_perm(request.method.lower(), resource):
#                 return view_func(request, *args, **kwargs)
#             else:
#                 return render(request, 'blockers.html')
#
#         return wrapper
#
#     return decorater


@my_model_cache(key='user', timeout=120 + randint(-30, 30))
def get_user(userid):
    return User.objects.select_related('permissions').get(userid=userid)
